/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package researchgrants.parts.LoggedData;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import researchgrants.parts.db.Db;

/**
 * A container to hold the data and manage data manipulation of a piece of data.
 * This piece of data can be changed and will be inflicted.
 * @author ohad
 */
public class LoggedData {
    
    public static LoggedData createNew(String firstValue) {
        int newLoggedDataId=-1;
        try {
            Connection conn=Db.openDbConnection();
            
            PreparedStatement prepareStatement = Db.createPreparedStatement(conn, "INSERT INTO tblLoggedData (LastLoggedDataChangeID) VALUES (-1)");
            prepareStatement.executeUpdate();
            newLoggedDataId = Db.getLastIdentity();
            prepareStatement.close();
            
            PreparedStatement newLoggedDataChangeStatement = Db.createPreparedStatement(conn, "INSERT INTO tblLoggedDataChanges (LoggedDataID, [Value]) VALUES (?, ?)");
            newLoggedDataChangeStatement.setInt(1, newLoggedDataId);
            newLoggedDataChangeStatement.setString(2, firstValue);
            newLoggedDataChangeStatement.executeUpdate();
            int newLoggedDataChangeId=Db.getLastIdentity();
            newLoggedDataChangeStatement.close();
            
            PreparedStatement updateLoggedDataStatement=Db.createPreparedStatement(conn, "UPDATE tblLoggedData SET LastLoggedDataChangeID=? WHERE LoggedDataID=?");
            updateLoggedDataStatement.setInt(1, newLoggedDataChangeId);
            updateLoggedDataStatement.setInt(2, newLoggedDataId);
            updateLoggedDataStatement.executeUpdate();
            updateLoggedDataStatement.close();
            
            Db.closeDbConnection(conn);
        } catch (SQLException ex) {
            Logger.getLogger(LoggedData.class.getName()).log(Level.SEVERE, null, ex);
        }
        return(getByID(newLoggedDataId));
    }
    
    // a factory that queries the database about the logged data
    public static LoggedData getByID(int id) throws IllegalArgumentException {
        return (new LoggedData(id));
    }

    private LoggedData(int id)  throws IllegalArgumentException {
        this.id = id;
//        syncDataFromDb();
    }
    
    int id;
    
    String currentValue;

    public int getId() {
        return(id);
    }

    private void syncDataFromDb() {
        try {
            Connection conn=Db.openDbConnection();
            PreparedStatement stat = Db.createPreparedStatement(conn, "SELECT Value FROM TblLoggedData INNER JOIN TblLoggedDataChanges ON TblLoggedData.LastLoggedDataChangeID=TblLoggedDataChanges.LoggedDataChangeID Where TblLoggedData.LoggedDataID=?");
            stat.setInt(1, id);
            stat.executeQuery();
            ResultSet resultSet=stat.getResultSet();
            currentValue = (String) Db.getSingleRowSingleColumn(resultSet);
            resultSet.close();
            stat.close();
            Db.closeDbConnection(conn);
        } catch (SQLException ex) {
            Logger.getLogger(LoggedData.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            throw new RuntimeException("Problem with Data: " + ex.getLocalizedMessage());
        }
    }
    
    public boolean hasValue() {
        return(true);
    }
    
    public String value () {
        syncDataFromDb();
        return(currentValue);
    }
    
    public void setNewValue(String value) {
        try {
            Connection conn=Db.openDbConnection();
            
            PreparedStatement insertChangeStatement = Db.createPreparedStatement(conn, "INSERT INTO tblLoggedDataChanges (LoggedDataID, [Value]) VALUES (?,?)");
            insertChangeStatement.setInt(1, id);
            insertChangeStatement.setString(2, value);
            insertChangeStatement.executeUpdate();
            int newLoggedDataChangeID = Db.getLastIdentity();
            insertChangeStatement.close();
            
            PreparedStatement updateLoggedDataAboutChangeStatement= Db.createPreparedStatement(conn, "UPDATE TblLoggedData SET LastLoggedDataChangeID=? WHERE LoggedDataID=?");
            updateLoggedDataAboutChangeStatement.setInt(1, newLoggedDataChangeID);
            updateLoggedDataAboutChangeStatement.setInt(2, id);
            updateLoggedDataAboutChangeStatement.executeUpdate();

            Db.closeDbConnection(conn);
        } catch (SQLException ex) {
            ex.getSQLState();
            ex.getMessage();
            
            Logger.getLogger(LoggedData.class.getName()).log(Level.SEVERE, "Problem updating the new value", ex);
        }
        syncDataFromDb();
    }
    
    public LoggedDataChange[] getAllChanges() {
        return(null);
    }
    
   public class LoggedDataChange {
        String value;
        Date chagneDate;
    }
}
